import { Component } from 'react';

import { Button,Boxs,Group,Toast,DatetimeField,Datetime,SelectField,TextareaField,TextField,PhotoField,EmployeeField} from 'saltui';
import DB from '../../../app/db';
import SelectMember from '../../../components/selectMember';

const {Count} = TextareaField;
export default class PageHome extends Component {
    constructor(props) {
		  super(props);
	    this.state = {
        title:'',
        typeList:[
          {'value':'questionnaireVote','text':'投票'},
          {'value':'questionnaireSurvey','text':'调查'},
          // {'value':'questionnaireExam','text':'考试'}
          ],  //问卷类型
        typeSelect:null,
        titleDescription:'',
        answerScopeList:[],
        answerScopeId:'',
        quesScopeList:[],
        quesScopeId:'',
        closeDate:'',
        createdBy:'',
      };
	    //设置标题
      dd.biz.navigation.setTitle({
            title: '新建',
            onSuccess: function(result) {},
            onFail: function() {}
        });
    }
       // 新值和事件对象
    handleChange(field,value) {
      this.setState({ [field]:value });
          
    }

      /**
     * 将timestamp数值转换成指定的日期格式字符串
     *
     * @param timestamp 时间戳
     * @param format 日期格式,如:yyyy-MM-dd HH:mm:ss
     * @returns {*}
     */
    timestampFormat(timestamp, format){
        var d = new Date(timestamp);
        var date = {
            "M+": d.getMonth() + 1,
            "d+": d.getDate(),
            "h+": d.getHours(),
            "H+": d.getHours(),
            "m+": d.getMinutes(),
            "s+": d.getSeconds(),
            "q+": Math.floor((d.getMonth() + 3) / 3),
            "S+": d.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    }

    // 日期选择事件
  handleChangeTime(field,value) {
    let time = this.timestampFormat(value.value,"yyyy-MM-dd");
    this.setState({
      closeDate:time
    });      
  }

  componentWillMount() {
    let t = this;
    DB.QuesModuleAPI.getUserName({}).then((content) => {
        t.setState({
          createdBy:content
        })
    }).catch();
  }

  //中文字符等验证
validateText(text, msg){
    if(!(/^([\u4E00-\u9FA5]|\w|\.)+$/).test(text)){
      Toast.show({
        type: 'error',
        content: msg + '请输入中文/字母/数字/下划线/点',
        onHide: function () {}
      });
      return false;
    }else{
      return true;
    }
  }

  getPerson(value,type){
      if(type=='answer'){
        this.setState({
          answerScopeList:value
        });
      }else if(type=='ques'){
        this.setState({
          quesScopeList:value
        });
      }
  }
    //提交表单
    submitLog(){
      let t = this;
     
    let name = t.state.title;
      if(name ==''){
        Toast.show({
          type: 'error',
          content: '问卷名称不能为空'
        });
        return;
      // }else if(!this.validateText(name, '问卷名称')){
      // return;
    }else if(name.length > 20){
      Toast.show({
        type: 'error',
        content: '问卷名称不能超过20个字符',
        onHide: function () {}
      });
      return;
    }else{
      if(isEmojiCharacter(name)){
        Toast.show({
        type: 'error',
        content: '问卷名称不能输入表情',
        onHide: function () {}
      });
        return;
      }
      if(!this.validateText(name,'问卷名称')){
        return;
      }
    }


      //问卷类型
      let typeSelect = t.state.typeSelect;
      let quesType = '';
      if(typeof(typeSelect) != 'undefined' && typeSelect != null ){
        quesType = typeSelect.value;
      }else{
        Toast.show({
          type: 'error',
          content: '问卷类型不能为空'
        });
        return;
      }
         //问卷类型
      let closeDate = t.state.closeDate;
      if(typeof(closeDate) != 'undefined' && closeDate != null && closeDate != ''){
        let newDate = new Date(this.timestampFormat(new Date(),"yyyy-MM-dd"));
        let selectDate = new Date(closeDate);
        if(newDate.getTime()>selectDate.getTime()){
          Toast.show({
            type: 'error',
            content: '截止日期不能小于当天日期'
          });
          return;
        }
      }else{
        Toast.show({
          type: 'error',
          content: '截止日期不能为空'
        });
        return;
      }

      let answerScopeList = JSON.stringify(this.state.answerScopeList);
      let quesScopeList = JSON.stringify(this.state.quesScopeList);
      if(this.state.quesScopeList==null || this.state.quesScopeList.length==0 || this.state.quesScopeList==[]){
        Toast.show({
          type: 'error',
          content: '允许答卷范围不能为空'
        });
        return;
      }
      if(this.state.answerScopeList==null || this.state.answerScopeList.length==0 || this.state.answerScopeList==[]){
        Toast.show({
          type: 'error',
          content: '答卷查看范围不能为空'
        });
        return;
      }

      //描述
      let description = t.state.titleDescription;
      if(description.length > 200){
        Toast.show({
          type: 'error',
          content: '问卷描述不能超过200个字符',
          onHide: function () {}
        });
        return;
    }
    if(description!=''){
      if(isEmojiCharacter(description)){
        Toast.show({
        type: 'error',
        content: '问卷描述不能输入表情',
        onHide: function () {}
     });
      return;
      }
    }
      var param = {
          name:name,
          answerScopeList:answerScopeList,
          quesScopeList:quesScopeList,
          quesType:quesType,
          closeDate:closeDate,
          description:description
        };
      DB.QuesModuleAPI.saveQues({
      	entity:JSON.stringify(param)
      }) 
      .then((content) => {
        Toast.show({
          type: 'success',
            content: '保存成功',
         });
        backPage();
      }).catch((error) => {
        if(typeof(error.errorMsg) == 'undefined'){
          Toast.show({
            type: 'error',
            content: '提交出错'
          });
        }else{
          Toast.show({
            type: 'error',
            content: error.errorMsg
          });
        }
      });
    }

    //页脚   取消
    cancel(){
      backPage();
    }
    render(){
       	const t = this;
       	return (
	       		<div  className="approval-details t-PB68" >
		             <div className="page-add">
                 <Group.List>
                    <TextField
                      required
                      label="问卷名称"
                      placeholder="请输入问卷名称"
                      value={t.state.title}
                      onChange={(value) => {
                        if(value.length <= 20){
                          t.handleChange('title', value);
                        }
                      }}
                    />
                  </Group.List>
                  <Group.List >
                    <SelectField
                      required
                      label="问卷类型"
                      placeholder="请选择问卷类型"
                      options={this.state.typeList}
                      onSelect={this.handleChange.bind(t,'typeSelect')}
                      value={this.state.typeSelect}
                    />
					        </Group.List>
                  <Group.List>
                    <DatetimeField required label="截止日期" placeholder="请选择截止日期" onSelect={t.handleChangeTime.bind(t, 'closeDate')} value={t.state.closeDate} columns={DatetimeField.YMD} />
                  </Group.List>
                   <Group.List>
                     <TextField
                       readOnly
                       label="创建人"
                       placeholder=""
                       value={t.state.createdBy}
                     />
                   </Group.List>
                  <Group.List>
                    <SelectMember 
                      label="允许答卷范围" 
                      checkType="checkbox" 
                      code="user,org" 
                      showType="list" 
                      required={true}
                      isDelete={true} 
                      onChange={(value)=>{this.getPerson(value,'ques');}}
                      />
                  </Group.List>
                  <Group.List>
                    <SelectMember 
                      label="答卷查看范围" 
                      checkType="checkbox" 
                      code="user,org" 
                      showType="list" 
                      required={true}
                      isDelete={true} 
                      onChange={(value)=>{this.getPerson(value,'answer');}}
                      />
                  </Group.List>
                  <div className="t-FAL-all">
                  <Group.List >
                    <TextareaField
                      layout="v"
                      label="问卷描述"
                      minRows={6}
                      maxRows={10}
                      placeholder="0-200字符"
                      value={t.state.titleDescription}
                      onChange={(value) => {
                        if(value.length <= 200){
                          t.handleChange('titleDescription', value);
                        }
                      }}
                    >
                    <Count total={200} length={this.state.titleDescription.length}/>
                    </TextareaField>
					        </Group.List>
                  </div>
		      	</div>
            
            <div >
                <Button.Group >
                  <Button type="primary" display="inline" onClick={t.submitLog.bind(t)}>保存</Button>
                  <Button type="secondary" display="inline" onClick={t.cancel.bind(t)}>取消</Button>  
              </Button.Group>
            </div>

	        </div>
       	)
       }
}
